package br.com.localizagora.DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import br.com.localizagora.banco.Conexao;
import br.com.localizagora.model.Package;

public class PackageDAO {
	
	private static PreparedStatement ps;
	private static Connection con;

	public static void inserePackage(Package pack){
		String update = "update package set last = 'false' where last = 'true' and idDevice = " + pack.getIdDevice() + " and typeData = "+pack.getTypeData();
		
		String sql = "INSERT INTO `localizagora`.`package`" 
					+"(`idDevice`,"
					+"`typeData`,"
					+"`realDateTime`,"
					+"`dateTime`,"
					+"`latitude`,"
					+"`longitude`,"
					+"`velocidade`,"
					+"`combustEletric`,"
					+"`tracking`,"
					+"`alarm`,"
					+"`charge`,"
					+"`acc`,"
					+"`voltage`,"
					+"`gsmsignal`)"
					+"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
		conectar(sql);
		
		try {
			ps.execute(update);
			
			ps.setInt(1,pack.getIdDevice());
			ps.setInt(2,pack.getTypeData());
			ps.setTimestamp(3,pack.getRealDateTime());
			ps.setTimestamp(4,pack.getDateTime());
			ps.setString(5,pack.getLatitude());
			ps.setString(6,pack.getLongitude());
			ps.setDouble(7,pack.getSpeed());	
			ps.setBoolean(8, pack.isOilEletricity());
			ps.setBoolean(9, pack.isGpsTracking());
			ps.setInt(10, pack.getAlarm());
			ps.setBoolean(11, pack.isCharge());
			ps.setBoolean(12, pack.isAcc());
			ps.setInt(13, pack.getVoltageLevel());
			ps.setInt(14, pack.getSignalLevel());
			
			ps.execute();
			System.out.println("Package ok");
			fechar();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private static void conectar(String sql) {
		try {
			con = Conexao.getConnection();
			ps = con.prepareStatement(sql);
		} catch (SQLException ex) {
			Logger.getLogger(PackageDAO.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	private static void fechar() {
		try {
			ps.close();
			con.close();
		} catch (SQLException ex) {
			Logger.getLogger(PackageDAO.class.getName()).log(Level.SEVERE, null, ex);
		}
	}    
}
